package com.row.common.utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName FileUtil
 * @Description 文件工具类
 * @Author Row
 * @Date 2019/6/12 13:53
 **/
@Controller
public class FileUtils {

    /**
     * 文件上传
     * @param file   上传的文件
     * @param filePath    上传路径
     */
    @PostMapping("/upload")
    @ResponseBody
    public void upload(MultipartFile file,String filePath){
        String filename = file.getOriginalFilename();
        String newName = UUID.randomUUID() + "." + filename.substring(filename.lastIndexOf(".") + 1);
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+newName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     * @param req
     * @param resp
     * @param url 文件地址
     * @param fileName 下载的文件名
     * @throws IOException
     */
    @PostMapping("/download")
    public void download(HttpServletRequest req, HttpServletResponse resp,String url,String fileName) throws  IOException {
        File file = new File(url);
        String filename = processFileName(req,fileName);  //文件名
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Disposition", "attachment;filename="+filename+"");
        resp.setContentType("application/octet-stream; charset=utf-8");
        resp.setContentLength((int) file.length());
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] buffer = new byte[128];
            int count = 0;
            while ((count = fis.read(buffer)) > 0) {
                resp.getOutputStream().write(buffer, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
            fis.close();
        }
    }

    /**
     *  删除文件
     * @param url 文件路径
     * @return
     */
    public static boolean deleteFile(String url) {
        File file = new File(url);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 下载文件转码
     * @param request
     * @param fileNames  文件名
     * @return
     */
    public static String processFileName(HttpServletRequest request, String fileNames) {
        String codedfilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                    && -1 != agent.indexOf("Trident")) {// ie

                String name = java.net.URLEncoder.encode(fileNames, "UTF8");

                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codedfilename;
    }
}
